<template>
  <van-nav-bar title="收件人地址" left-arrow @click-left="onClickLeft">
    <template #left>
      <van-icon name="arrow-left" size="20" color="#1ba784" />
    </template>
  </van-nav-bar>
  <van-address-list
    v-model="chosenAddressId"
    :list="list"
    :switchable="!switchable"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @click-item="onClickItem"
  >
  </van-address-list>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { showToast } from 'vant'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user.store'
import { getContactList } from '@/api/modules/contact'
const router = useRouter()
const userStore = useUserStore()
const chosenAddressId = ref('1')
const list = ref([])
// ==================== 计算属性 ====================
// 是否允许切换
const switchable = computed(() => {
  // return (
  //   router.options.history.state.back === '/Mine' ||
  //   router.options.history.state.back === '/mine'
  // )
  return true
})

// ==================== 方法 ====================
// 获取收件人地址列表
const getList = async () => {
  try {
    const {
      userInfo: { app_user_id }
    } = userStore
    const { data } = await getContactList({ user_id: app_user_id })
    data.data.forEach((item) => {
      item.id = item.contact_id
      if (item.is_default === '1') {
        item.isDefault = true
      }
      item.address =
        item.province + item.city + item.county + item.address_detail
      item.name = item.contact_name
      item.tel = item.contact_phone
      if (item.is_default) {
        chosenAddressId.value = item.id
      }
    })
    list.value = data.data
  } catch (error) {
    console.log('error', error)
  }
}

// 新增地址
const onAdd = () => {
  router.push('/AddressEdit')
}
const onEdit = (item, index) => {
  router.push({
    name: 'AddressEdit',
    query: {
      id: item.id
    }
  })
}
const onClickLeft = () => history.back()

const onClickItem = async (item) => {
  if (
    router.options.history.state.back == '/Mine' ||
    router.options.history.state.back === '/mine'
  ) {
    return
  } else {
    await userStore.setCurContact(item.contact_id)
    router.back()
    return
  }
}

// ==================== 生命周期 ====================
onMounted(() => {
  getList()
})
</script>

<style lang="less" scoped>
:deep(.van-button--primary) {
  background-color: @green;
  border: solid @green;
}
:deep(.van-address-item__tag) {
  background-color: @green !important;
  padding: 2px 3px !important;
  border-color: @green !important;
}
</style>
